﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip;

namespace ZipTool
{
    public class ShareZipHelper
    {
        /// <summary>
        /// 压缩单个文件到一个zip包中
        /// </summary>
        /// <param name="srcFileName">原文件名</param>
        /// <param name="zipFileName">压缩文件名</param>
        /// <param name="zipEnum">压缩的方式</param>
        /// <returns>压缩成功标志</returns>
        public static bool ZipSingleFile(string srcFileName, string zipFileName, ZipEnum zipEnum)
        {
            bool flag = false;
            try
            {
                switch (zipEnum)
                {
                    case ZipEnum.GZIP: ZipSingleFileByGzip(srcFileName, zipFileName, zipEnum); break;
                    case ZipEnum.BZIP2:
                        ZipSingleFileByBzip2(srcFileName, zipFileName, zipEnum); break;
                }
                return flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }

        private static void ZipSingleFileByBzip2(string srcFileName, string zipFileName, ZipEnum zipEnum)
        {
            using (FileStream inStream = File.OpenRead(srcFileName))
            {
                using (FileStream outStream = File.Open(zipFileName, FileMode.Create))
                {
                    try
                    {
                        BZip2.Compress(inStream, outStream, true, 4096);
                    }
                    catch
                    {
                        
                    }
                    finally
                    {
                        inStream.Close();
                        outStream.Close();
                    }
                }
            }
        }

        private static void ZipSingleFileByGzip(string srcFileName, string zipFileName, ZipEnum zipEnum)
        {
            using (FileStream srcFile = File.OpenRead(srcFileName))
            {
                using (GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipFileName, FileMode.Create)))
                {
                    try
                    {
                        byte[] fileData = new byte[srcFile.Length];
                        srcFile.Read(fileData, 0, (int)srcFile.Length);
                        zipFile.Write(fileData, 0, fileData.Length);
                    }
                    catch
                    {
                       
                    }
                    finally
                    {
                        srcFile.Close();
                        zipFile.Close();
                    }
                }
            }
        }

       
    }
}
